/*
 * TCSS 422 Web Spider Project
 * Group Money: Al McKenzie, Michael Pitts, Taylor Zielske
 */
package control.threads;

import model.URLInputCooker;
import model.URLStore;
import control.data.SearchHopper;

/**
 * This class can run multiple threads that will process urls, first getting then 
 * buffering and finally parsing each url.
 * 
 * @author Michael Pitts
 * @version Nov 1, 2011
 */
public class SimpleMultiThreadDirector extends AbstractThreadDirector {
	
	/**
	 * Stores all the processing threads.
	 */
	private final ProcessThread[] my_threads;

	/**
	 * Creates a new simple MultiThreaded Thread director.
	 * @param the_cooker is the URLInputCooker for this program.
	 * @param the_hopper is the SearchHopper for this program.
	 * @param the_store is the URLStore for this program.
	 * @param the_search_words are the words to search for during the run of this program.
	 * @param the_max is the max number of threads that can run for the program.
	 */
	public SimpleMultiThreadDirector(final URLInputCooker the_cooker,
			final SearchHopper the_hopper, final URLStore the_store,
			final String[] the_search_words, final int the_max) {
		super(the_cooker, the_hopper, the_store, the_search_words);
		my_threads = new ProcessThread[the_max];
		for (int i = 0; i < my_threads.length; i++) { // sets up threads
			my_threads[i] = new ProcessThread(getProcessOne());
			my_threads[i].setPriority(my_threads[i].getPriority() - 1);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override public void start() {
		for (ProcessThread thread : my_threads) {
			thread.start();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override public void stop() {
		for (ProcessThread thread : my_threads) {
			thread.setGo(false);
		}
	}

	/**
	 * Gets a runnable that tries to process one url, trying to buffer and parse it.
	 * @return a new runnable that calls cookOne() and parseOne().
	 * @see AbstractThreadDirector#cookOne()
	 * @see AbstractThreadDirector#parseOne()
	 */
	private Runnable getProcessOne() {
		return new Runnable() {
			@Override public void run() {
				cookOne(); //buffers one url
				parseOne(); // tries to parse one url
			}
		};
	}
}
